<?php defined('BASEPATH') or exit('No direct script access allowed');
class Channel_m extends L_Model
{
	public function __construct(){	
		parent::__construct();
		$this->set_table_name("channel");
	}
	/**
	 * $channel_type = 'MN'
	 * $channel_type = 'MB'
	 * $channel_type = 'MT'
	 * 
	 * @param unknown_type $channel_type
	 */
	public function find_today_channels_by_channel_type($channel_type) {
		$now = time();
		$close_times = $this->find_today_close_time_by_channel_type($channel_type);
		//2001-03-10 17:16:18 (the MySQL DATETIME format)
		$start_close_time = $close_times[0];
		$end_close_time = $close_times[1];
		/**
		 * If current time is earlier than [start_close_hour] => get channel of CURRENT date
		 * If current time is later than [end_close_hour] => get channel of NEXT date
		 * If current time is between [start_close_hour, end_close_hour] => do not return any channel
		 */
		$current_day_of_week = date( 'w', $now) + 1; //Plug 1 because date('w') return 0 for Sunday, 6 for Saturday
		
		$selected_day_of_week = -1;
		if ($now < $start_close_time) {
			$selected_day_of_week = $current_day_of_week;
		} else {
			if ($current_day_of_week < 7) {
				$selected_day_of_week = $current_day_of_week + 1;
			} else {
				$selected_day_of_week = 1;
			}
		}
		
		$sql = "SELECT * 
		        FROM l_channel c
		             INNER JOIN l_channel_schedule cs ON c.id = cs.channel_id
		        WHERE cs.day = ? AND c.type = ?";
		$today_channels = $this->db->query($sql, array($selected_day_of_week, $channel_type))->result_object();
		return $today_channels;		
	}
	
	public function find_today_close_time_by_channel_type($channel_type) {
		$channel_scheduler_config = $this->config->item('channel_schedule');
		$channel_type_scheduler_config = $channel_scheduler_config[$channel_type];
		$now = time();
		$current_time_stamp = date('Y-m-d H:i:s'); //2001-03-10 17:16:18 (the MySQL DATETIME format)
		$current_yyyy_mm_dd = date('Y-m-d', $now);
		$current_hh_mm_ss = date('H:i:s', $now);
		
		//2001-03-10 17:16:18 (the MySQL DATETIME format)
		$start_close_time = strtotime ($current_yyyy_mm_dd . ' ' . $channel_type_scheduler_config['start_close_hour']);
		$end_close_time = strtotime ($current_yyyy_mm_dd . ' ' . $channel_type_scheduler_config['end_close_hour']);
		return array($start_close_time, $end_close_time);
	}
}